import chartApi from '@/apis/chartApi';
import MyLoading from '@/components/MyLoading';
import { useEffect, useState } from 'react';
import { Button, Card, Checkbox, Dialog, Empty, Image, Stepper, Toast } from 'react-vant';
import './Chart.css';
import { getGoodsImagePath, promptResult } from '@/utils/common';
import MyPromotePrice from '@/components/MyPromotePrice';
import orderApi from '@/apis/orderApi';

const Chart: React.FC = () => {
  const [data, setData] = useState<ResponseGroupCartsDto[]>([]);
  const [fetching, setFetching] = useState(true);
  const [checkedIds, setCheckedIds] = useState<number[]>([]); // 选中的购物车编号

  useEffect(() => {
    const fetchData = async () => {
      const res = await chartApi.getChartList();
      setData(res.data);
      setFetching(false);
    };
    fetchData();
  }, []);

  const sumPrice = () => {
    let charts: ResponseCartsDto[] = [];
    data.forEach((d) => (charts = charts.concat(d.charts)));
    let sum = 0;
    charts
      .filter((d) => checkedIds.includes(d.id))
      .forEach(
        (d) => (sum += d.count * (d.good.promotePrice ? d.good.promotePrice : d.good.price))
      );
    return sum.toFixed(2);
  };

  const plus = (sid: number, id: number) => {
    console.log(data.find((d) => d.sid === sid)!.charts.find((d) => d.id === id)!);
    promptResult(
      chartApi.increaseChart(id),
      () => {},
      () => {
        let temp = [...data];
        temp.find((d) => d.sid === sid)!.charts.find((d) => d.id === id)!.count += 1;
        setData(temp);
      }
    );
  };

  const minus = (sid: number, id: number) => {
    let temp = [...data];
    let good = temp.find((d) => d.sid === sid)!.charts.find((d) => d.id === id)!;
    if (good.count === 1) {
      Dialog.confirm({
        title: '提示',
        message: '您确定要移除该商品吗？',
        onCancel: () => {},
        onConfirm: () => {
          promptResult(
            chartApi.deleteChart(id),
            () => {},
            () => {
              temp = temp.map((d) => {
                if (d.sid === sid) {
                  d.charts = d.charts.filter((d) => d.id != id);
                }
                return d;
              });
              temp = temp.filter((d) => d.charts.length > 0);
              setData(temp);
              setCheckedIds(checkedIds.filter((d) => d != id));
            }
          );
        },
      });
    } else {
      promptResult(
        chartApi.decreaseChart(id),
        () => {},
        () => {
          good.count -= 1;
          setData(temp);
        }
      );
    }
  };

  const setChartGoodCount = (sid: number, id: number, count: number) => {
    promptResult(
      chartApi.setChartGoodCount(id, count),
      () => {},
      () => {
        let temp = [...data];
        temp.find((d) => d.sid === sid)!.charts.find((d) => d.id === id)!.count = count;
        setData(temp);
      }
    );
  };

  const handleCheckAll = (checked: boolean) => {
    if (checked) {
      let temp: ResponseCartsDto[] = [];
      data.forEach((d) => (temp = temp.concat(d.charts)));
      setCheckedIds(temp.map((d) => d.id));
    } else {
      setCheckedIds([]);
    }
  };

  const handleSubmit = async () => {
    // 每个不同的供应商生成一个订单
    let temp = [...data];
    let tempCheckIds = [...checkedIds];
    for (let i = 0; i < temp.length; i++) {
      const d = temp[i];
      for (let j = 0; j < d.charts.length; j++) {
        const chart = d.charts[j];
        if (tempCheckIds.includes(chart.id)) {
          let charts = d.charts.filter((d) => tempCheckIds.includes(d.id));
          const res = await orderApi.submitOrder({
            goodIds: charts.map((d) => d.good.id),
            goodCounts: charts.map((d) => d.count),
            chartIds: charts.map((d) => d.id),
          });
          if (res.status >= 0) {
            Toast.success(`订单${i + 1}已生成`);
            d.charts = d.charts.filter((d) => !charts.find((e) => e.id === d.id));
            tempCheckIds = tempCheckIds.filter((d) => !charts.find((e) => e.id === d));
          } else {
            Toast.fail(`订单${i + 1}生成失败`);
          }
          break;
        }
      }
    }
    setData(temp.filter((d) => d.charts.length > 0));
    setCheckedIds(tempCheckIds);
  };

  return (
    <>
      {fetching ? (
        <MyLoading />
      ) : data.length > 0 ? (
        data.map((d) => (
          <Card key={d.sid} className="type-card">
            <div className="shop-name">{d.sname + ' >'}</div>
            <div className="good-list">
              {d.charts.map((e) => (
                <div key={e.id} className="good-item">
                  <div className="checkbox">
                    <Checkbox
                      checked={checkedIds.includes(e.id)}
                      iconSize="28px"
                      onChange={(checked) => {
                        if (checked) setCheckedIds([...checkedIds, e.id]);
                        else setCheckedIds(checkedIds.filter((d) => d != e.id));
                      }}
                    />
                  </div>
                  <div className="image">
                    <Image src={getGoodsImagePath(e.good.id, e.good.photo)} />
                  </div>
                  <div className="info">
                    <div className="info-item">{e.good.name + ' ' + e.good.spec}</div>
                    <div className="info-item">
                      <MyPromotePrice price={e.good.price} propmotePrice={e.good.promotePrice} />
                    </div>
                    <div className="info-item" style={{ display: 'flex', width: '100%' }}>
                      <div style={{ marginLeft: 'auto' }}>
                        <Stepper
                          value={e.count}
                          min={0}
                          max={99999}
                          onPlus={() => plus(d.sid, e.id)}
                          onMinus={() => minus(d.sid, e.id)}
                          onBlur={(event) =>
                            setChartGoodCount(d.sid, e.id, parseInt(event.target.value))
                          }
                        />
                      </div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </Card>
        ))
      ) : (
        <Empty></Empty>
      )}
      <div className="submit-order-block"></div>
      <div className="submit-order">
        <div className="check-all-btn">
          <Checkbox
            checked={(() => {
              let sum = 0;
              data.forEach((d) => (sum += d.charts.length));
              return data.length > 0 && sum === checkedIds.length;
            })()}
            iconSize={28}
            onChange={handleCheckAll}
          />
          全选
        </div>
        <div className="submit-text">
          合计：<span className="sum-price">¥{sumPrice()}</span>
        </div>
        <div>
          <Button round type="danger" onClick={handleSubmit}>
            提交订单
          </Button>
        </div>
      </div>
    </>
  );
};

export default Chart;
